package com.crazyauntzhang.easyshopbackend.interceptor;

import com.crazyauntzhang.easyshopbackend.domain.User;
import com.crazyauntzhang.easyshopbackend.service.UserService;
import com.crazyauntzhang.easyshopbackend.util.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器：拦截Controller方法进行token验证
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

	private final UserService userService;

	@Autowired
	public LoginInterceptor(UserService userService) {
		this.userService = userService;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
		//由于配置了跨域，如果拦截的是预检的OPTIONS请求，则放行
		if (request.getMethod().equalsIgnoreCase("OPTIONS"))
			return true;
		//从请求头获取token
		String token = request.getHeader("Authorization");
		//进行token本身的校验
		if (token == null || token.isBlank() || !Token.verifyToken(token))
			throw new RuntimeException("Invalid Token");
		//如果token本身没有问题，则检查token中的用户是否存在于数据库中，若不存在则拦截
		String userID = (String) Token.parseToken(token).get("userID");
		User user = userService.findUserById(userID, true);
		if (user == null)
			throw new RuntimeException("Invalid Token");
		//如果所有检查都通过则放行
		return true;
	}

}
